<template>
  <div>
    <complex-table
      v-loading="uiOpts.loading"
      :data="replicaSetList"
      @search="reloadReplicaSets"
    >
      <el-table-column
        :label="$t('commons.table.version')"
        prop="name"
        min-width="80"
        show-overflow-tooltip
      >
        <template #default="{ row }">
          <span>
            {{ row.metadata.annotations["deployment.kubernetes.io/revision"] }}
          </span>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('commons.table.image')"
        prop="image"
        min-width="80"
        show-overflow-tooltip
      >
        <template #default="{ row }">
          <span
            v-for="(k, index) in row.spec.template.spec.containers"
            :key="index"
          >
            <span class="label-custom wd" type="info">{{ k.image }}</span>
          </span>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('commons.table.time')"
        prop="time"
        min-width="80"
        show-overflow-tooltip
      >
        <template #default="{ row }">
          <span>{{ row.metadata.creationTimestamp }}</span>
        </template>
      </el-table-column>
      <ko-table-operations
        :buttons="uiOpts.optionBtns"
        :label="$t('commons.table.action')"
      />
    </complex-table>

    <el-dialog
      v-model="uiOpts.dialogSpecificVisible"
      :title="$t('business.workload.specific_information')"
      width="70%"
      :close-on-click-modal="false"
    >
      <yaml-editor :value="yamlEditForm" :read-only="true" />
      <template v-slot:footer>
        <div class="dialog-footer">
          <el-button size="small" @click="uiOpts.dialogSpecificVisible = false">
            {{ $t("commons.button.cancel") }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import ComplexTable from "@/views/domain/kubeHud/views/components/complex-table/index.vue";
import KoTableOperations from "@/views/domain/kubeHud/views/components/ko-table-operations/index.vue";
// import { checkPermissions } from "@/utils/permission";
// import { listNsReplicaSetsWorkload } from "@/api/replicasets";
// import { patchDeployment } from "@/api/deployments";
import YamlEditor from "@/views/domain/kubeHud/views/components/yaml-editor/index.vue";
import { computed, reactive, ref } from "vue";
import { useI18n } from "vue-i18n";
import {
  Pod,
  PresetAnnotationKey,
  ReplicaSet,
  useK8SApi
} from "../../../api/k8s";
import { hasNsPodsListPermission } from "../../../utils/permission";
import { ElMessageBox } from "element-plus";
import { useRoute } from "vue-router";
import { objectToString } from "../../../utils";

const { t } = useI18n();
const { replicaSetRepo, deploymentRepo } = useK8SApi();
const route = useRoute();

type Prop = {
  cluster?: string;
  namespace: string;
  selector?: { [key: string]: any };
  fieldSelector?: { [key: string]: any };
  name: string;
};
const props = defineProps<Prop>();
const replicaSetList = ref<ReplicaSet[]>();
const yamlEditForm = ref();

const clusterName = computed<string>(
  () => props.cluster || (route.query?.cluster as any) || ""
);

const uiOpts = reactive({
  loading: false,
  dialogModifyVersionVisible: false,
  dialogSpecificVisible: false,
  optionBtns: [
    {
      label: t("commons.button.rollback"),
      icon: "el-icon-refresh-left",
      click: row => {
        OptionRollback(row);
      },
      disabled: row => {
        return !(row.status.readyReplicas === undefined);
      }
    },
    {
      label: t("business.workload.specific_information"),
      icon: "el-icon-tickets",
      click: row => {
        SpecificInformation(row);
      }
    }
  ]
});

const reloadReplicaSets = async () => {
  if (!(await hasNsPodsListPermission())) {
    return;
  }

  uiOpts.loading = true;
  const { items } = await replicaSetRepo.listNsReplicaSets({
    clusterName: props.cluster,
    namespace: props.namespace,
    labelSelector: objectToString(props.selector),
    fieldSelector: objectToString(props.fieldSelector)
  });

  replicaSetList.value = items.sort((a, b) => {
    return (
      parseFloat(b.metadata.annotations[PresetAnnotationKey.Revision] ?? "0") -
      parseFloat(a.metadata.annotations[PresetAnnotationKey.Revision] ?? "0")
    );
  });
};

const OptionRollback = async (row: ReplicaSet) => {
  ElMessageBox.alert(
    t("commons.confirm_message.rollback"),
    t("commons.message_box.prompt"),
    {
      confirmButtonText: t("commons.button.confirm"),
      cancelButtonText: t("commons.button.cancel"),
      type: "warning"
    }
  ).then(() => {
    deploymentRepo
      .patchDeployment({
        cluster: clusterName.value,
        namespace: props.namespace,
        name: props.name,
        data: { spec: { template: row.spec.template } }
      })
      .then(() => {
        uiOpts.dialogModifyVersionVisible = false;
      });
  });
};

const SpecificInformation = row => {
  yamlEditForm.value = row;
  uiOpts.dialogSpecificVisible = true;
};
</script>

<style scoped>
.btnSize {
  width: 28px;
  height: 28px;
}
</style>
